package com.fiume.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * <p>
 * Description:
 * </p>
 *
 * @author fiume
 * @version v1.0.0
 * @create 2021-01-20 20:49
 * @see com.fiume.gateway.filter
 */
//注明过滤器执行为第一位
@Order(0)
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().toSingleValueMap().get("access-token");
        if (token.equals("admin")) {
            //权限正确
            return chain.filter(exchange);
        } else {
            //权限错误,拦截并设置状态码
            ServerHttpResponse response = exchange.getResponse();
            boolean statusCode = response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //结束任务
            return response.setComplete();
        }
    }

    //2.通过@Configuration类结合lambda表达式
    /*@Bean
    @Order(-2)
    public GlobalFilter globalFilter0(){
        return ((exchange, chain) -> {
           log.info("pre阶段");
           return chain.filter(exchange)
                   .then(Mono.fromRunnable(() -> {
                       log.info("post阶段!");
                   }));
        });
    }*/
}
